let startX, startY, right, top;

Component({
  options: {
    styleIsolation: 'apply-shared'
  },
  properties: {
    icons: {
      type: Array,
      value: []
    }
  },
  data: {
    id: '',
    pos: { right: 0, top: 0, height: 0, width: 0 },
    run: false
  },
  methods: {
    
    onTouchStart(e) {

      this.setData({
        run: false
      })
      const { clientX = 0, clientY = 0 } = e.changedTouches[0] || {};
      startX = clientX;
      startY = clientY;
      top = this.data.pos.top;
      right = this.data.pos.right;
      const dom = wx.createSelectorQuery().in(this).select('#' + this.data.id);
      dom.boundingClientRect((rect) => {
        const { width, height } = rect;
        this.setData({
          pos: { ...this.data.pos, width, height }
        })
      }).exec();
    },
    onTouchMove(e) {
      const windowInfo = wx.getWindowInfo();
      const { clientX = 0, clientY = 0 } = e.changedTouches[0] || {};
      const deltaX = clientX - startX;
      const deltaY = clientY - startY;
      const newTop = top + deltaY;
      const newRight = right - deltaX;
      const pos = this.data.pos;
      this.setData({
        pos: { 
          ...pos, 
          top: Math.min(Math.max(newTop, 0), windowInfo.windowHeight - pos.height), 
          right: Math.min(Math.max(newRight, 0), windowInfo.windowWidth - pos.width)
        }
      });
    },
    onTouchEnd() {
      const windowInfo = wx.getWindowInfo();
      const dom = wx.createSelectorQuery().in(this).select('#' + this.data.id);
      dom.boundingClientRect((rect) => {
        this.setData({
          run: true
        })
        const { left, top, width, height } = rect;
        const middle = windowInfo.windowWidth / 2;
        const boxMiddle = width / 2 + left;
        if (boxMiddle > middle) {
          this.setData({
            pos: { top, right: 0, width, height }
          });
        } else {
          this.setData({
            pos: { top, right: windowInfo.windowWidth - width, width, height }
          });
        }
      }).exec();
    },
    onTransitionEnd() {
      this.setData({
        run: false
      })
    },
    onIconClick: async function (e) {
      const { dataset: { item } } = e.currentTarget;
      this.triggerEvent('click', item);
    },
  },

  lifetimes: {
    attached() {
      const windowInfo = wx.getWindowInfo();
      this.setData({
        'pos.top': parseInt(windowInfo.windowHeight * 1 / 4),
        id: 'float-icons-' + new Date().getTime() + '-' + Math.round(Math.random() * 1000000)
      });
    },
  },
});
